package com.auxgroup.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.BaseResult;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.schedule.ScheduleResult;
import com.auxgroup.jpush.entity.JpushConfig;
import com.auxgroup.jpush.entity.JpushEntity;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调用推送服务接口
 * Created by niuGuangzhe on 2017/8/9.
 */
@Service
public class JpushService {
    private static final Logger log = LoggerFactory.getLogger(JpushService.class);
    @Autowired
    private JpushConfig jpushConfig;

    private JPushClient JpushClient() {
//        jpushConfig = new JpushConfig("d394d34c95d7b8d80f4d975d", "a7a23c7fbe435c06d1a33b30");
        JPushClient jPushClient = new JPushClient(jpushConfig.getMasterSecret(), jpushConfig.getAppKey(),
                null, ClientConfig.getInstance());
        return jPushClient;
    }

    /**
     * 推送消息的API函数主体
     *
     * @param entity
     * @param userAliasList
     * @return
     */
    public BaseResult pushInfo(JpushEntity entity, List<String> userAliasList) {
        PushPayload payload = buildPushObjectImmediately(entity, userAliasList);
        return commonPush(entity, JpushClient(), payload);
    }

    /**
     * 推送单条消息
     *
     * @param entity
     * @param userAlias
     * @return
     */
    public BaseResult pushInfoSingle(JpushEntity entity, String userAlias) {
        PushPayload payload = buildPushObjectImmediatelySingle(entity, userAlias);
        return commonPush(entity, JpushClient(), payload);
    }

    public BaseResult pushByTag(JpushEntity entity, String tag) {
        PushPayload payload = buildTagPushPayload(entity, tag);
        return commonPush(entity,JpushClient(),payload);
    }

    public BaseResult pushByAlias(JpushEntity entity, String alias) {
        PushPayload payload = buildAliasPushPayload(entity, alias);
        return commonPush(entity,JpushClient(),payload);
    }



    private BaseResult commonPush(JpushEntity entity,JPushClient jPushClient,PushPayload payload){
        try {
            //scheduled name暂时定为发送消息的title
            if (entity.getJpushPushTime() != null) {
                ScheduleResult result2 = jPushClient.createSingleSchedule(entity.getJpushTitle(), entity.getJpushPushTime(), payload);
                return result2;
            } else {
                PushResult result1 = jPushClient.sendPush(payload);
                return result1;
            }
        } catch (APIConnectionException e) {
            log.error("连接错误，应该稍后重试");
        } catch (APIRequestException e) {
            log.error("极光推送平台错误的返回码，请检查错误");
            log.error("http status:" + e.getStatus());
            log.error("error code:" + e.getErrorCode());
            log.error("error message:" + e.getErrorMessage());
        }
        return null;
    }

    /**
     * 构建发送消息
     *
     * @param entity
     * @param userAliasList
     * @return
     */
    public static PushPayload buildPushObjectImmediately(JpushEntity entity, List<String> userAliasList) {
        return commonBuilder(entity, userAliasList);
    }

    /**
     * 单独推送消息
     *
     * @param entity
     * @param userAlias
     * @return
     */
    public static PushPayload buildPushObjectImmediatelySingle(JpushEntity entity, String userAlias) {
        return commonBuilder(entity, Arrays.asList(userAlias));
    }


    private static Notification buildNotication(JpushEntity entity, Map<String, String> extra) {
        if(null == extra) extra = new HashedMap();
        IosAlert alert = IosAlert.newBuilder()
                .setTitleAndBody(entity.getJpushTitle(), "", entity.getJpushMessage())
                .setActionLocKey("PLAY")
                .build();
        return Notification.newBuilder()
                .addPlatformNotification(IosNotification.newBuilder()
                        .setAlert(alert)
                        .addExtras(extra)
                        .setCategory(entity.getCategory())
                        .setContentAvailable(true)
                        .build())
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(entity.getJpushMessage())
                        .setTitle(entity.getJpushTitle())
                        .addExtras(extra)
                        .setCategory(entity.getCategory())
                        .build())
                .build();
    }

    private static PushPayload buildBasePushPayload(JpushEntity entity, Audience audience, Map<String, String> extra){
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())  //全平台推送
                .setAudience(audience)
                .setNotification(buildNotication(entity, extra))
//                .setMessage(Message.newBuilder()
//                        .setTitle(entity.getJpushTitle())
//                        .setMsgContent(entity.getJpushMessage())
//                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                .build();
    }

    public static PushPayload buildTagPushPayload(JpushEntity entity, List<String> tags){
        return buildBasePushPayload(entity, Audience.tag(tags), null);
    }

    public static PushPayload buildTagPushPayload(JpushEntity entity, String tag) {
        return buildTagPushPayload(entity, Arrays.asList(tag));
    }

    public static PushPayload buildAliasPushPayload(JpushEntity entity, List<String> alias) {
        return buildBasePushPayload(entity, Audience.alias(alias), null);
    }

    public static PushPayload buildAliasPushPayload(JpushEntity entity, String alias) {
        return buildAliasPushPayload(entity, Arrays.asList(alias));
    }

    private static PushPayload commonBuilder(JpushEntity entity, List<String> userAliasList){
        Map<String, String> extra =new HashMap<>();
        extra.put("linkedUrl", entity.getJpushMessageUrl());
        extra.put("imageUrl ",entity.getImageUrl());
        extra.put("type",entity.getType());
        extra.put("sourceType",entity.getSourceType());
        extra.put("sourceValue",entity.getSourceValue());
        extra.put("platform",entity.getPlatform());
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())  //全平台推送
                .setAudience(Audience.alias(userAliasList))
                .setNotification(buildNotication(entity, extra))
//                .setMessage(Message.newBuilder()
//                        .setTitle(entity.getJpushTitle())
//                        .setMsgContent(entity.getJpushMessage())
//                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(true).build())
                .build();
    }

    /**
     * 极光推送消息
     * @param title 消息标题
     * @param message 消息内容
     * @param pushTime 消息推送时间
     * @param userAlias 消息推送的目标
     * @return
     */
    public BaseResult pushMsg(String title,String message,String pushTime,String ... userAlias){
        JpushEntity jpushEntity = new JpushEntity(title,message, pushTime);
        return pushInfo(jpushEntity,Arrays.asList(userAlias));
    }

}
